import router, { constantRoutes, constant404Routes, resetRouter } from '@/router'
import Layout from '@/layout'
import SuIndex from '@/layout/so-index.vue'
import store from '@/store'

/**
 * @param routes  动态数组
 */
export function filterAsyncRoutes(routes) {
  const res = []
  if (routes.length > 0) {
    routes.forEach(route => {
      const tmp = { ...route }
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children)
      }
      // 带有 path 属性才会 push 到路由中
      if (tmp.path) {
        tmp.name = route.code
        if (sa.$sys.getCurSer().isAuth === 1) {
          if (tmp.component === 'Layout') {
            tmp.component = Layout
          } else {
            tmp.component = loadView(tmp.component)
          }
        } else {
          if (tmp.component === 'Layout') {
            tmp.component = SuIndex
          } else {
            tmp.component = loadView(tmp.component)
          }
        }
        res.push(tmp)
      }
    })
  }
  return res
}

// 路由懒加载
export const loadView = (view) => {
  return (resolve) => require([`@/views/${view}`], resolve)
}

const state = {
  // 当前路由表
  routes: [],
  router_init: false
}

const mutations = {
  // 设置路由
  setRoutes: (state, routes) => {
    // 二次筛选一下
    let routeList = filterAsyncRoutes(routes)

    // 树状菜单
    state.routes = constantRoutes.concat(routeList)

    // push 到 router 里
    router.addRoutes(routeList);

    // 404
    router.addRoutes(constant404Routes);
  },

  // 初始化路由
  INIT_ROUTES: function (state, menus) {
    store.commit('permission/setRoutes', menus);
    state.router_init = true
  },

  // 修改routeInit
  SET_ROUTE_INIT: function (state, flag) {
    state.router_init = flag
  },
}

const actions = {
  initRoutes({ commit }, menus) {
    resetRouter()
    commit('INIT_ROUTES', menus)
  },

  setRouteInit({ commit }, flag) {
    commit('SET_ROUTE_INIT', flag)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
